package com.opencee.cloud.msg.thread.handler;

import cn.hutool.core.bean.BeanUtil;
import com.opencee.cloud.msg.api.vo.params.MessageTaskParams;
import com.opencee.cloud.msg.api.vo.params.SmsBatchParams;
import com.opencee.cloud.msg.api.vo.params.SmsSingleParams;
import com.opencee.cloud.msg.config.MessageTaskContext;
import com.opencee.cloud.msg.service.MsgSmsSenderService;
import com.opencee.cloud.msg.thread.MessageTaskHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * 发送短信适配器
 *
 * @author yadu
 */
@Slf4j
public class SmsTaskHandler implements MessageTaskHandler, Serializable {

    private MsgSmsSenderService smsSenderService;

    public SmsTaskHandler() {
    }

    public SmsTaskHandler(MsgSmsSenderService smsSenderService) {
        this.smsSenderService = smsSenderService;
    }

    /**
     * 前置参数验证
     *
     * @param taskParams
     * @return
     */
    @Override
    public boolean validate(MessageTaskContext context, MessageTaskParams taskParams) throws RuntimeException {
        return true;
    }

    @Override
    public boolean execute(MessageTaskContext context, MessageTaskParams taskParams) {
        Object params = taskParams.getParams();
        SmsBatchParams smsBatchSendParams = null;
        if (params instanceof SmsSingleParams) {
            // 单条转批量
            SmsSingleParams smsSingleSendParams = (SmsSingleParams) params;
            smsBatchSendParams = new SmsBatchParams();
            BeanUtil.copyProperties(smsSingleSendParams, smsBatchSendParams);

        }
        if (params instanceof SmsBatchParams) {
            // 批量发送
            smsBatchSendParams = (SmsBatchParams) params;
        }
        if (smsBatchSendParams != null) {
            try {
                return smsSenderService.send(smsBatchSendParams);
            } catch (Exception e) {
                log.error("发送短信错误:", e);
            }
        }
        return false;
    }


    @Override
    public boolean support(Object message) {
        return message instanceof SmsSingleParams || message instanceof SmsBatchParams;
    }
}
